package chaincode

import (
	"encoding/json"

	"github.com/hyperledger/fabric-chaincode-go/shim"
	"github.com/hyperledger/fabric-protos-go/peer"
)

type SmartContract struct{}

func (s *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response {
	return shim.Success(nil)
}

func (s *SmartContract) Invoke(stub shim.ChaincodeStubInterface) peer.Response {
	function, args := stub.GetFunctionAndParameters()
	switch function {
	case "add":
		return s.AddAsset(stub, args)
	case "read":
		return s.ReadAsset(stub, args)
	case "transfer": // 添加transfer处理
		return s.TransferAsset(stub, args)
	default:
		return shim.Error("无效的方法名")
	}
}

type Asset struct {
	ID    string `json:"id"` // 修正JSON标签
	Owner string `json:"owner"`
	Name  string `json:"name"`
}

func (s *SmartContract) AddAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	if len(args) != 3 {
		return shim.Error("参数数量错误，需要ID、Owner和Name")
	}

	asset := Asset{
		ID:    args[0],
		Owner: args[1],
		Name:  args[2],
	}

	assetJSON, err := json.Marshal(asset)
	if err != nil {
		return shim.Error("序列化失败: " + err.Error()) // 添加return
	}

	err = stub.PutState(args[0], assetJSON)
	if err != nil {
		return shim.Error("保存资产失败: " + err.Error())
	}

	return shim.Success(nil)
}

func (s *SmartContract) ReadAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	if len(args) != 1 {
		return shim.Error("需要资产ID作为参数")
	}

	assetJSON, err := stub.GetState(args[0])
	if err != nil {
		return shim.Error("查询失败: " + err.Error())
	}
	if assetJSON == nil {
		return shim.Error("资产不存在")
	}

	return shim.Success(assetJSON)
}

func (s *SmartContract) TransferAsset(stub shim.ChaincodeStubInterface, args []string) peer.Response {
	if len(args) != 2 {
		return shim.Error("需要资产ID和新Owner作为参数")
	}

	assetJSON, err := stub.GetState(args[0])
	if err != nil {
		return shim.Error("查询失败: " + err.Error())
	}
	if assetJSON == nil {
		return shim.Error("资产不存在")
	}

	var asset Asset
	err = json.Unmarshal(assetJSON, &asset)
	if err != nil {
		return shim.Error("反序列化失败: " + err.Error())
	}

	asset.Owner = args[1]
	updateJSON, err := json.Marshal(asset)
	if err != nil {
		return shim.Error("序列化更新失败: " + err.Error())
	}

	err = stub.PutState(args[0], updateJSON)
	if err != nil {
		return shim.Error("更新资产失败: " + err.Error())
	}

	return shim.Success(nil)
}
